package com.google.code.cisx.gwt.client;

import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.core.client.GWT;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.rpc.ServiceDefTarget;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.ClickListener;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.ui.Widget;

/**
 * Entry point classes define <code>onModuleLoad()</code>.
 * 
 * @deprecated This was experimental.
 */
public class Desktop implements EntryPoint {

  /**
   * This is the entry point method.
   */
  public void onModuleLoad() {

    final Button button = new Button("Click to Login");
    final Label label = new Label();

    button.setTitle("This will execute the RPC call to the Java v1.5 GWT server");

    button.addClickListener(new ClickListener() {
      public void onClick(Widget sender) {

        callLoginService(label);

      }

    });

    callLoginService(label);

    RootPanel.getBodyElement().setInnerText("Hello World yet again!");
    RootPanel.get().add(button);
    RootPanel.get().add(label);
  }

  private void callLoginService(final Label label) {
    // (1) Create the client proxy. Note that although you are
    // creating the
    // service interface proper, you cast the result to the
    // asynchronous
    // version of
    // the interface. The cast is always safe because the generated
    // proxy
    // implements the asynchronous interface automatically.
    LoginRemoteServiceAsync sampleRemoteService = (LoginRemoteServiceAsync) GWT.create(LoginRemoteService.class);

    // (2) Specify the URL at which our service implementation is
    // running.
    // Note that the target URL must reside on the same domain and
    // port from
    // which the host page was served.
    ServiceDefTarget endpoint = (ServiceDefTarget) sampleRemoteService;

    String moduleRelativeURL = GWT.getModuleBaseURL() + "rpc/Login";
    endpoint.setServiceEntryPoint(moduleRelativeURL);

    // (3) Create an asynchronous callback to handle the result.
    AsyncCallback<String> callback = new AsyncCallback<String>() {
      public void onSuccess(String result) {
        // do some UI stuff to show success
        label.setText("Result reported from server: " + result);
      }

      public void onFailure(Throwable caught) {
        // do some UI stuff to show failure
        label.setText("This didnt work. " + caught.toString());
      }
    };

    // (4) Make the call. Control flow will continue immediately and
    // later
    // 'callback' will be invoked when the RPC completes.
    sampleRemoteService.login("admin", "admin123", callback);
  }
}
